package apobates.gui.formatter.storage;

import apobates.gui.formatter.packet.ResourceType;
import java.util.Optional;

/**
 * 最近记录的字符串编解码器
 */
public class RecentRecordStringCodec implements RecentRecordCodec<String>{
    @Override
    public String encode(RecentRecord recentRecord) {
        if(recentRecord.getType() == ResourceType.FILE){
            return String.format("file://%s", recentRecord.getPath());
        }
        if(recentRecord.getType() == ResourceType.URL){ // _e=&_t=
            String tmp = recentRecord.getPath().indexOf("?") == -1 ? recentRecord.getPath().concat("?") : recentRecord.getPath().concat("&");
            String charset = Optional.ofNullable(recentRecord.getCharset()).orElseGet(()->"UTF-8");
            int timeout = recentRecord.getTimeout()>=8000 & recentRecord.getTimeout()<= 800000 ? recentRecord.getTimeout() : 8000;
            return tmp.concat(String.format("_e=%s&_t=%d", charset, timeout));
        }
        return null;
    }

    @Override
    public Optional<RecentRecord> decode(String value) {
        if(value.startsWith("file:")){
            RecentRecord fileRecord = new RecentRecord();
            fileRecord.setPath(value.substring(7));
            fileRecord.setType(ResourceType.FILE);
            fileRecord.setTimeout(8000);

            return Optional.of(fileRecord);
        }
        if(value.startsWith("http:")){
            // 字符集的参数位
            int e1 = value.indexOf("_e");
            RecentRecord urlRecord = new RecentRecord();
            if(e1 != -1) {
                urlRecord.setPath(value.substring(0, e1 - 1));
                this.setURLParam(urlRecord, value, e1);
            }else{
                urlRecord.setPath(value);
                urlRecord.setCharset("UTF-8");
                urlRecord.setTimeout(8000);
            }
            return Optional.of(urlRecord);
        }
        return Optional.empty();
    }
    private void setURLParam(RecentRecord urlRecord, String value, int startIndex){
        String ess = value.substring(startIndex, value.length()).replace("_e=", "").replace("_t=", "");
        int el = ess.indexOf("&");
        if(el != -1) {
            urlRecord.setCharset(ess.substring(0, el));
        }else{
            urlRecord.setCharset("UTF-8");
        }
        try{
            urlRecord.setTimeout(Integer.valueOf(ess.substring(el+1, ess.length())));
        }catch (Exception e){
            urlRecord.setTimeout(8000);
        }
    }
}
